package com.qf.spring.anno.confg;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.ResolvableType;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;

/**
 * @author 钻五大人
 * @date 2022/4/28 22:10
 * Spring的配置类
 * 作用：是替换之前的beans.xml配置文件
 */
@Configuration  //标识当前类是一个配置类
@ComponentScan("com.qf.spring.anno")
public class SpringConfig {

    // 1、dataSource
    // @Bean: 定义一个bean,方法名dataSource就是bean的id,方法的返回值就是bean的class
    // <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" />
    @Bean
    public static DruidDataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/db2202?useUnicode=true&characterEncoding=UTF-8");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        return dataSource;
    }

    // 2、sqlSessionFactory
    @Bean
    public static SqlSessionFactoryBean sqlSessionFactory() throws IOException {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        // 注入数据源
        factoryBean.setDataSource(dataSource());
        // 获取mapper.xml资源文件
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources("classpath:mapper/*.xml");
        // 注入资源文件
        factoryBean.setMapperLocations(resources);
        // 配置实体类的别名
        factoryBean.setTypeAliasesPackage("com.qf.spring.anno.entity");
        return factoryBean;
    }

    // 3、MapperScannerConfigurer
    @Bean
    public static MapperScannerConfigurer mapperScannerConfigurer(){
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        // 配置DAO层接口的包名
        configurer.setBasePackage("com.qf.spring.anno.dao");
        return configurer;
    }

    // txManager
}
